﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using nanoCMS.Core;
using nanoCMS.StaticPages.Concrete;

namespace nanoCMS.StaticPages.Providers
{
    public class StaticPageProvider
    {
        private readonly WorldContext worldContext;
        private PagesEntities _entities; //DO NOT ACCESS DIRECTLY
        private PagesEntities Entities
        {
            get { return _entities ?? (_entities = new PagesEntities(worldContext.EntityConnectionString)); }
        }

        public StaticPageProvider(WorldContext worldContext)
        {
            this.worldContext = worldContext;
        }

        public void Create(string title, string content)
        {
            StaticPage page = new StaticPage()
            {
                TenantID = 0, // TODO
                Title = title,
                Content = content
            };
            Entities.StaticPages.AddObject(page);
            Entities.SaveChanges();
        }

        public void Edit(int pageID, string title, string content)
        {
            StaticPage page = Get(pageID);
            if(page != null)
            {
                page.Title = title;
                page.Content = content;
                Entities.ObjectStateManager.ChangeObjectState(page, EntityState.Modified);
                Entities.SaveChanges(); 
            }
        }

        public StaticPage Get(int pageID)
        {
            return Entities.StaticPages.Where(p => p.PageID == pageID).SingleOrDefault();
        }

        public List<StaticPage> GetAll()
        {
            return Entities.StaticPages.ToList();
        }

        public void Delete(int pageID)
        {
            StaticPage page = Get(pageID);
            if (page != null)
            {
                Entities.ObjectStateManager.ChangeObjectState(page, EntityState.Deleted);
                Entities.SaveChanges();
            }
        }
    }

}
